﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace CSharpLearningProject;

public class ImageProcessor
{
    // 声明C++ DLL函数
    [DllImport("BarcodeDetectDll.dll", CallingConvention = CallingConvention.Cdecl)]
    private static extern IntPtr ProcessImage(
        byte[] inputData,
        int width,
        int height,
        int channels,
        out int outLength
    );

    [DllImport("BarcodeDetectDll.dll", CallingConvention = CallingConvention.Cdecl)]
    private static extern void FreeStrings(IntPtr ptr, int length);

    // 封装方法：将C++返回的char**转换为List<string>
    public static List<string> ProcessImageData(byte[] imageData, int width, int height, int channels)
    {
        IntPtr resultPtr;
        int resultLength;
        resultPtr = ProcessImage(imageData, width, height, channels, out resultLength);

        var results = new List<string>();
        for (int i = 0; i < resultLength; i++)
        {
            IntPtr stringPtr = Marshal.ReadIntPtr(resultPtr, i * IntPtr.Size);
            string str = Marshal.PtrToStringAnsi(stringPtr);
            results.Add(str);
        }
        
        // 释放C++分配的内存
        FreeStrings(resultPtr, resultLength);
        return results;
    }
}